<?php

class EncuestaController extends Controller {

    /**
     * @var string the default layout for the views.
     */
    public $layout = '/../views/layouts/encuesta';

//    public $admin = true;

    /**
     * @var private property containing the associated model instance.
     */
//    private $_entity = null;

    /**
     * Define filters for this Controllers
     * @return array Array of filters
     */

    /**
     * Action to submit a form
     * @param type $id
     */
    public function actionSubmit($id) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);

        $this->performAjaxValidation($form_model);

        if (isset($_POST['DynamicFormModel'])) {
            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate()) {
                $transaction = Yii::app()->db->beginTransaction();

                try {
                    $answer = new Answer;
                    $answer->entity_id = $this->_entity->id;
                    $answer->creation_date = date('Y-m-d H:i:s');

                    if (!$answer->save())
                        throw new Exception("Error Saving Answer");

                    foreach ($_POST['DynamicFormModel'] as $field => $content) {
                        $field_value = new FieldValue;
                        $field_value->content = $content;
                        $field_value->answer_id = $answer->id;
                        $field_value->field_id = $field;

                        if (!$field_value->save())
                            throw new Exception("Error Saving Field Value");
                    }

                    $transaction->commit();
                    Yii::app()->user->setFlash('success', Yii::t('noseyModule.app', 'Answers saved successfully!'));

                    $url = $postPerPage = Yii::app()->controller->module->after_submit_url;
                    if (!$url || $url == null)
                        $this->redirect(array('thanks'));
                    else
                        $this->redirect($url);
                } catch (Exception $ex) {
                    $transaction->rollBack();
                    Yii::app()->user->setFlash('error', Yii::t('noseyModule.app', 'There was an error saving the answers.'));
                }
            }
        }

        $this->render('submit', array(
            'model' => $model,
            'form_model' => $form_model,
        ));
    }

    /**
     * @author Alex Yepez <ayepez@tradesystem.com.ec>
     * Creaccion del registro de las la entidad que respondera la encuesta
     * @param type $entidad_tipo
     * @param type $entidad_id
     * @param type $contacto
     * @param type $form_id
     * @param type $subentidad_tipo
     * @param type $subentidad_id
     */
    public function actionCreateEntidadAnswer($entidad_tipo, $entidad_id, $contacto, $form_id, $subentidad_tipo = null, $subentidad_id = null) {
        $model = new NoseyEntidadAnswer();
        $model->entidad_tipo = Nosey_Util::decodeParam($entidad_tipo);
        $model->entidad_id = Nosey_Util::decodeParam($entidad_id);
        $model->contacto = Nosey_Util::decodeParam($contacto);
        $model->nosey_form_id = Nosey_Util::decodeParam($form_id);
        if ($subentidad_tipo) {
            $model->subentidad_tipo = Nosey_Util::decodeParam($subentidad_tipo);
        }
        if ($subentidad_id) {
            $model->subentidad_id = Nosey_Util::decodeParam($subentidad_id);
        }
        if ($model->save()) {
//            $this->actionFormularioCliente($model->nosey_form_id, $model->id);
            $this->actionFormularioCliente(Nosey_Util::encodeParam($model->nosey_form_id), Nosey_Util::encodeParam($model->id));
        }
    }

    public function actionMissingTranslation($category, $message, $language) {
        Yii::t($category, $message, null, null, $language);
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Form::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Protected method to load the associated Project model class
     * @param integer projectId the primary identifier of the associated Project
     * @return object the Project data model based on the primary key
     */
    protected function loadEntity($entityId) {
        $entity_model = $postPerPage = Yii::app()->controller->module->entity_model;

        if (!$entity_model)
            throw new CHttpException(400, 'You have to specify the model to associate in the config file.');
        if ((@include $entity_model . '.php') === false)
            throw new CHttpException(404, 'The associated model can not be loaded.');

        //if the project property is null, create it based on input id
        if ($this->_entity === null) {
            $this->_entity = $entity_model::model()->findByPk($entityId);

            if ($this->_entity === null)
                throw new CHttpException(404, 'The requested entity does not exist.');
        }
        return $this->_entity;
    }

    /**
     * In-class defined filter method, configured for use in the above filters()
     * method. It is called before the actionCreate() action method is run in
     * order to ensure a proper project context
     */
    public function filterEntityContext($filterChain) {
        //set the project identifier based on GET input request variables
        if (isset($_GET['eid']))
            $this->loadEntity($_GET['eid']);
        else
            throw new CHttpException(403, 'Must specify an entity before performing this action.');
        //complete the running of other filters and execute the requested action
        $filterChain->run();
    }

    public function actionFormularioCliente($id, $entity_id, $validador = false) {
        $id = Nosey_Util::decodeParam($id);
        $entity_id = Nosey_Util::decodeParam($entity_id);
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);

        $this->performAjaxValidation($form_model);

        if (isset($_POST['DynamicFormModel'])) {

            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate() && $validador) {

                $result = $this->SaveNoseyForm($_POST['DynamicFormModel'], $entity_id);
            } else {

                $result['success'] = false;
                $result['data'] = $form_model->errors;
            }
            echo json_encode($result);
        } else {

            $this->render('_submit_slider_encuesta', array(
                'model' => $model,
                'form_model' => $form_model,
                  'entity_id' => $entity_id,
            ));
        }
    }

    public function SaveNoseyForm($model_form, $id_entrada) {

        $result = array();
        $transaction = Yii::app()->db->beginTransaction();
        try {
            $answer = new Answer;
            $answer->entity_id = $id_entrada;
            $answer->creation_date = Util::FechaActual();

            if (!$answer->save())
                throw new Exception("Error Saving Answer");

            foreach ($model_form as $field => $content) {
                $field_value = new FieldValue;
                if (is_array($content)) {
                    $field_value->content = json_encode($content);
                } else {
                    $field_value->content = $content;
                }
                $field_value->answer_id = $answer->id;
                $field_value->field_id = $field;
                if (!$field_value->save())
                    throw new Exception("Error Saving Field Value");
            }
            $transaction->commit();
            $result['success'] = TRUE;
            $result['message'] = 'Información almacenada con exito';
            return $result;
        } catch (Exception $ex) {
            $transaction->rollBack();
            $result['success'] = false;
            $result['message'] = 'No se pudo guardar la informacion';
            return $result;
        }
    }

}
